<template>
  <div id="editor"></div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import Editor from '@toast-ui/editor'
import '@toast-ui/editor/dist/toastui-editor.css'
import '@toast-ui/editor/dist/i18n/zh-cn'
import { uploadImg } from '@/api/knowledgeBase'

let editor

onMounted(() => {
  editor = new Editor({
    el: document.querySelector('#editor'),
    height: '100%',
    initialEditType: 'wysiwyg',
    previewStyle: 'tab',
    language: 'zh-CN',
    placeholder: '',
    hideModeSwitch: true,
    hooks: {
      addImageBlobHook: (blob, callback) => {
        if (blob.size / 1024 / 1024 < 10) {
          const fileData = new FormData()

          fileData.append('file', blob)
          uploadImg(fileData).then((res) => {
            callback(res.data.url)
          })
        } else {
          message.error('图片大小不能超过10MB!')
        }
        // callback('https://avatars.githubusercontent.com/u/10065708?v=4')
        // uploadImage(
        //   blob,
        //   function (imageUrl) {
        //     callback(imageUrl) // 将链接传递给编辑器
        //   },
        //   function (error) {
        //     console.error('图片上传失败：', error)
        //   }
        // )
      }
    }
  })
  editor.removeToolbarItem('table')
  editor.removeToolbarItem('link')
  editor.removeToolbarItem('code')
  editor.removeToolbarItem('codeblock')
  editor.removeToolbarItem('indent')
  editor.removeToolbarItem('outdent')
})

const getContent = () => {
  let htmlContent = ''
  if (editor.isWysiwygMode()) {
    htmlContent = editor.getHTML().replace(/<p[^>]*>\s*./g, (match) => {
      return match.replace(/\s/g, '&nbsp;')
    })
    // htmlContent = editor.getHTML().replace(/<p>(.*?)<\/p>/g, '&nbsp;')
  } else {
    htmlContent = editor.getMarkdown()
  }
  return htmlContent
}

const setContent = (content: string) => {
  if (editor.isWysiwygMode()) {
    // content = content.replace(/&nbsp;/g, ' ')
    editor.setHTML(content ? content : '')
    setTimeout(() => {
      editor.setScrollTop(0)
    }, 10)
  }
}

defineExpose({
  getContent,
  setContent
})
</script>

<style lang="less" scoped>
#editor {
  background: #fff;
}
</style>
